<html>
<head>
    <title>Golang Chat</title>
    <link rel="stylesheet" href="../static/layui/css/layui.css">
    <script src="../static/layui/layui.js"></script>
    <script src="/static/jquery-3.6.3.min.js"></script>
    <script src="/static/fun.js"></script>
    <script src="/static/emoji.js"></script>
    <meta charset="UTF-8" />
</head>
<body>
<div style="width: 100%;height: 100%;">
    <div id="log">
        <div class="chat-title">
            <div class="layui-unselect layim-chat-title">
                <div class="layim-chat-other">
                    <div style="width: 50px;height: 50px;position: absolute;left: 0;top: 0;">
                        <img class="layim-chat-img" src="" width="50">
                        <div id="layim-chat-img-state" class="layim-chat-state-offline"></div>
                    </div>
                    <span class="layim-chat-username" layim-event=""></span>
                    <p id="layim-chat-text-state"class="layim-chat-status"></p>
                </div>
            </div>
        </div>
        <div class="chat-main">
            <div style="width: 100%;height: 100%;position: relative">
                <button class="chat-main-notification layui-btn" type="button"><i class="layui-icon layui-icon-triangle-d"></i>有新的消息</button>
            </div>
            <div class="chat-main-context">
                <div  style="text-align: center;padding: 5px 0"><div class="showMoreMsg" style="color: #6495ED;cursor:pointer">查看更多消息</div></div>

                <ul>

            </ul>
            </div>
        </div>
        <div class="chat-footer">
            <form id="form">
                <div class="chat-tool">
                    <span class="layui-icon layui-icon-face-smile-b layim-tool-face" title="选择表情"></span>

                    <span class="layui-icon layui-icon-picture layim-tool-img" id="LAY_messageUpload" title="选择图片"></span>
                    <span class="layui-icon layui-icon-group layim-tool-booking" title="线下预约"></span>
                </div>
                <div class="chat-textarea">
                    <div contenteditable="true" id="msg" onpaste="removeFormatting(event)"></div>
                </div>
                <div class="chat-bottom">
                    <div class="chat-input">
                        <span class="layim-session-close" layim-event="closeThisChat">关闭</span>
                        <span id="send-btn" class="layim-session-send" layim-event="closeThisChat">发送</span>
                        <span class="layim-session-set" id="setSend" lay-type="show"><em class="layui-edge"></em></span>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script>
        layui.laytpl.config({
            open: '{%',
            close: '%}'
        });
        Id = getCookie("Id")
        Name = getCookie("Name")
        //获取双方的头像
        var avatar=getavatar(Id)
        var to_avatar=getavatar(parent.to_Id)
        var LastSendMsg  //用来记录上一次发送的消息

        $(".layim-chat-other img").attr("src",to_avatar)
        function setchatmainHeight(){
            var h = $("#log").height()-$(".chat-title").height()-$(".chat-footer").height()
            $(".chat-main").height(h)
        }
        var chatMain = $(".chat-main ul")

        //添加信息
        function appendLog(data,state) {
            if (state=="messaging"){
                messageLog="<div class=\"layim-chat-state\"><i class=\"layui-icon layui-anim layui-anim-rotate layui-anim-loop layui-icon-loading\"></i></div>"
            }else {
                messageLog=""
            }
            if (data.type == "msg"){
                if (data.sender==getCookie("Id")){
                    //自己发的信息
                    msg  ="<li class=\"layim-chat-mine\" id="+data.SendTimestamp+">\n" +
                        "                <div class=\"layim-chat-user\">\n" +
                        "                <img src=\""+avatar+"\">\n" +
                        "                <cite><i>"+data.sendTime+"</i>"+Name+"</cite></div>\n" +
                        messageLog+
                        "                <div class=\"layim-chat-text\"> <pre>"+text2pic(data.content)+"</pre></div>\n" +
                        "            </li>"
                }else {
                    //接收的信息
                    msg ="<li id="+data.SendTimestamp+">\n" +
                        "                    <div class=\"layim-chat-user\">\n" +
                        "                        <img src=\""+to_avatar+"\">\n" +
                        "                        <cite>"+data.senderName+"<i>"+data.sendTime+"</i></cite>\n" +
                        "                    </div>\n" +
                        "                    <div class=\"layim-chat-text\"><pre>"+text2pic(data.content)+"</pre></div>\n" +
                        "                </li>"
                }
            }else if (data.type == "pic"){
                if (data.sender==getCookie("Id")){
                    //自己发的信息
                    msg  ="<li class=\"layim-chat-mine\" id="+data.SendTimestamp+">\n" +
                        "                <div class=\"layim-chat-user\">\n" +
                        "                <img src=\""+avatar+"\">\n" +
                        "                <cite><i>"+data.sendTime+"</i>"+Name+"</cite></div>\n" +
                        messageLog+
                        "                <div class=\"layim-chat-pic\"> <img width='175px'  onclick=\"showBigImage(this)\"   src="+data.content+"></div>\n" +
                        "            </li>"
                }else {
                    //接收的信息
                    msg ="<li id="+data.SendTimestamp+">\n" +
                        "                    <div class=\"layim-chat-user\">\n" +
                        "                        <img src=\""+to_avatar+"\">\n" +
                        "                        <cite>"+data.senderName+"<i>"+data.sendTime+"</i></cite>\n" +
                        "                    </div>\n" +
                        "                <div class=\"layim-chat-pic\"> <img width='175px'  onclick=\"showBigImage(this)\"  src="+data.content+"></div>\n" +
                        "                </li>"
                }
            }else if(data.type == "booking"){
                if (getCookie("Status")=="老师"){
                    buttonStr= "                        <button class=\"layui-btn layui-btn-primary layui-btn-sm booking-accept-refuse\">拒绝</button>\n" +
                               "                        <button class=\"layui-btn layui-btn-normal layui-btn-sm booking-accept-btn\">接受</button>\n"
                }else {
                    buttonStr=""
                }
                if (data.content.state>1){
                    buttonStr=""
                }
                var stateStr
                switch (data.content.state) {
                    case "1":
                        stateStr = "发起";
                        break;
                    case "2":
                        stateStr = "接受";
                        break;
                    case "3":
                        stateStr = "完成";
                        break;
                    case "4":
                        stateStr = "取消";
                        break;
                    case "5":
                        stateStr = "失效";
                        break;
                    default:
                        stateStr = "异常";
                        break;
                }
                //接受到预约类型的消息
                msg ="<div class=\"layui-card bookingCard\"id="+data.SendTimestamp+">\n" +
                    "                    <div class=\"layui-card-header\">线下预约</div>\n" +
                    "                    <div class=\"layui-card-body\">\n" +
                    "                        <p>时间："+data.content.bookingTime+"</p>\n" +
                    "                        <p>内容："+data.content.text+"</p>\n" +
                    "                        <p>地点："+data.content.place+"</p>\n" +
                    "<p>状态："+stateStr+"</p>\n"+
                    "                    </div>\n" +
                    "                    <div class=\"layui-card-footer\" style=\"text-align: center\" id="+data.content.Id+">\n" +
                    buttonStr+
                    "                    </div>\n" +
                    "                </div>"
            }
            //判断是不是历史消息
            if (state=="history"){
                chatMain.prepend(msg)
            }else {
                chatMain.append(msg)
                $(".chat-main-context img").on("load",OnloadImage)
                //如果是对方发的并且滚动条大于100就不执行，反之执行
                if (!(data.sender!=getCookie("Id")&&scrollMain().scrollSumH-scrollMain().scrollH>100)){
                        $(".chat-main-context").scrollTop(scrollMain().Bottom)
                }else {
                    $(".chat-main-notification").css("display","block")
                    console.log("有新消息！！！！！！！")
                }
            }
        }
        //滚动到消息底下
        function scrollMain(){
            // lastH =$(".chat-main-context ul li:last").offset().top    //消息体距离div可视顶部的高度
            scrollDom = $(".chat-main-context")
            divH = $(".chat-main").height()                           //聊天窗口高度
            var scrollHeight = scrollDom.prop('scrollHeight');
            var innerHeight = scrollDom.innerHeight();
            scrollableDistance = scrollHeight - innerHeight;  //导航条可以滚动的距离
            Bottom = divH+scrollableDistance                     //消息体距离顶部的高度
            return{
                Bottom:this.Bottom,
                scrollH:scrollDom.scrollTop(),
                scrollSumH:scrollableDistance
            }
            // scrollDom.scrollTop(Bottom)                          //设置导航条滚到到最底
        }

        //界面准备完毕执行，从redis中删除未读的信息。
        function delUnread(Id,to_uid){
            $.ajax({
                url:'/public/msg/delUnread',
                method:'post',
                dataType:'JSON',
                data:{
                    "Id":Id,
                    "to_uid":to_uid,
                }
            })
        }

        //图片加载完成再调整滚动条
        function OnloadImage(e){
            $(".chat-main-context").scrollTop(scrollMain().Bottom)
        }

        $(document).ready(function (){
            getMessages()//获取历史消息
            getClientName()   //获取聊天对象名字
            to_Id = parent.to_Id   //聊天对象Id号
            checkOnline(to_Id) //判断用户是否在线
            delUnread(Id,to_Id)            //删除未读消息
            setchatmainHeight()
            $(window).resize(function(){
                setchatmainHeight()
            });
            getFaceList()                                          //获取所有表情
            var msg = $("#msg")
            if (window["WebSocket"]) {
                var conn = parent.websocketConn
                conn.onmessage = function(evt) {
                    var data = JSON.parse(evt.data);
                    if ((data.type=="msg"||data.type=="pic"||data.type=="booking") && data.sender==to_Id){  //接收对面发的消息
                        appendLog(data)
                    }else if (LastSendMsg == evt.data){           //判断消息是否发送成功
                        $("#"+data.SendTimestamp).find(".layim-chat-state").remove()
                    }else if (data.type=="login"){
                        StateOnlineClass()
                    }else if (data.type=="exit"){
                        StateOfflineClass()
                    }else {                                       //把消息该为未读，发送到服务器
                        data.type="Unread"
                        var jsonStr = JSON.stringify(data);       //转为JSON字符串
                        conn.send(jsonStr);
                    }
                }
            } else {
                console.log("WebSockets Not Support.")
            }

            //发送消息
            function sendMessage(){
                if (!conn) {
                    console.log("没有连接")
                    return false;
                }
                if (!msg.html()) {
                    console.log("消息为空")
                    return false;
                }

                var content =  replaceEmojisWithText(msg.html()) //转化emoji
                var myDate = new Date;
                SendTime =myDate.getFullYear()+"-"+(myDate.getMonth()+1)+"-"+myDate.getDate()+" "+myDate.getHours()+":"+myDate.getMinutes()+":"+myDate.getSeconds()
                var SendTimestamp = new Date().getTime();
                var json = {"roomId":parent.roomId.toString(),"sender":Id,"senderName":Name,"recipient":to_Id,"content":content,"sendTime":SendTime,"type": "msg","SendTimestamp":SendTimestamp}; //创建对象；
                var jsonStr = JSON.stringify(json);       //转为JSON字符串
                appendLog(json,"messaging")
                LastSendMsg = jsonStr
                conn.send(jsonStr);
                msg.html("");
            }
            //发送消息
            function sendBooking(content){
                if (!conn) {
                    console.log("没有连接")
                    return false;
                }
                if (!content) {
                    console.log("消息为空")
                    return false;
                }
                var myDate = new Date;
                SendTime =myDate.getFullYear()+"-"+(myDate.getMonth()+1)+"-"+myDate.getDate()+" "+myDate.getHours()+":"+myDate.getMinutes()+":"+myDate.getSeconds()
                var SendTimestamp = new Date().getTime();
                var json = {"roomId":parent.roomId.toString(),"sender":Id,"senderName":Name,"recipient":to_Id,"content":content,"sendTime":SendTime,"type": "booking","SendTimestamp":SendTimestamp.toString()}; //创建对象；
                var jsonStr = JSON.stringify(json);       //转为JSON字符串
                appendLog(json,"messaging")
                LastSendMsg = jsonStr
                conn.send(jsonStr);
                msg.html("");
            }
            $(".layim-tool-booking").click(function (){
                if (getCookie("Status")=="老师"){
                    return
                }
                layer.open({
                    type: 1,
                    title: '线下预约',
                    shadeClose:true,
                    area: ['400px', '450px'],
                    closeBtn: 0,
                    content: `
            <form class="layui-form" action="">
  <div class="layui-form-item">
  <div class="layui-form-item">
    <label class="layui-form-label">日期选择</label>
    <div class="layui-input-block">
      <input type="text" id="dateBooking" name="dateBooking" required lay-verify="required" placeholder="请选择日期" autocomplete="off" class="layui-input">
    </div>
  </div>
    <label class="layui-form-label">姓名</label>
    <div class="layui-input-block">
      <input type="text" readonly="readonly" name="stu_name" required lay-verify="required" placeholder="请输入姓名" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">老师</label>
    <div class="layui-input-block">
      <input type="text" readonly="readonly" name="teacher_name" required lay-verify="required" placeholder="请输入老师名字" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">预约地点</label>
    <div class="layui-input-block">
      <input type="text" readonly="readonly" name="place" required lay-verify="required" placeholder="请输入预约地点" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">预约内容</label>
    <div class="layui-input-block">
      <textarea name="content" placeholder="请输入预约内容" class="layui-textarea"></textarea>
    </div>
  </div>
  <div class="layui-form-item layui-form-text" style="display: none">
    <label class="layui-form-label">状态</label>
    <div class="layui-input-block">
      <input name="state" placeholder="请输入预约内容" value="1">
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button class="layui-btn" lay-submit lay-filter="formBooking">预约</button>
    </div>
  </div>
</form>
        `,
                    success:function(layero, index){
                        $('input[name="stu_name"]').val(getCookie('Name'))
                        $('input[name="teacher_name"]').val($(".layim-chat-username").html())
                        $('input[name="place"]').val(getBookingPlace('100000'))
                        layui.use(['form', 'laydate'], function(){
                            var form = layui.form;
                            var laydate = layui.laydate;

                            //日期选择器
                            laydate.render({
                                elem: '#dateBooking' //指定元素
                                ,type: 'datetime'
                                ,min: 1 //7天前
                                ,max: 7 //7天后
                                ,format: 'yyyy-MM-dd HH:mm'
                            });

                            //监听提交
                            form.on('submit(formBooking)', function(data){
                                data.field.stu_name=getCookie('Id')
                                data.field.teacher_name=parent.to_Id
                                $.ajax({
                                    url: '/public/AddBookingPlace',
                                    type: 'post',
                                    data: data.field,
                                    dataType: 'json',
                                    success: function(res){
                                        if (res.code==200){
                                            layer.close(index)
                                            layer.msg(res.msg,{icon: 1, time: 1000},function(){
                                                var context = {"Id":res.bookingId,"place":data.field.place,"text":data.field.content,"bookingTime":data.field.dateBooking,"state":data.field.state};
                                                sendBooking(context)
                                            }); //提交成功
                                        }else {
                                            layer.msg(res.msg,{icon: 0, time: 1000},function(){}); //失败
                                        }
                                    }
                                });
                                return false;
                            });
                        });
                    }
                });
            });

            //发送下拉框
            EVisibility = ""
            CVisibility = "hidden"
            //初始绑定
            const SendKey = localStorage.getItem('SendKey');
            if (SendKey=='ctrl+enter'){
                ctrlSendFun()
            }else {
                enterSendFun()
            }
            layui.use('dropdown', function() {
                var dropdown = layui.dropdown
                dropdown.render({
                    elem: '#setSend' //可绑定在任意元素中，此处以上述按钮为例
                    ,data: [{
                        id: 100
                        ,templet:'<div><i class="layui-icon" id="Enter" style="visibility:{% EVisibility %} "></i>按Enter键发送消息</div>'
                    },{
                        id: 101
                        ,templet:'<div><i class="layui-icon" id="CtrlEnter" style="visibility:{% CVisibility %};"></i>按Ctrl+Enter键发送消息</div>'
                    }]
                    , click: function(data, othis){
                        switch (data.id){
                            case 100:
                                // 保存用户设置
                                localStorage.setItem('SendKey', 'enter');
                                enterSendFun()
                                break
                            case 101:
                                localStorage.setItem('SendKey', 'ctrl+enter');
                                ctrlSendFun()
                                break
                        }
                    }
                })
            })
            function enterSendFun(){
                EVisibility = ''
                CVisibility = 'hidden'
                $('#msg').unbind('keydown');
                $('#msg').bind('keypress',enterSend);
                $('#msg').bind('keydown',ctrlN);
            }
            function ctrlSendFun(){
                EVisibility = 'hidden'
                CVisibility = ''
                $('#msg').unbind('keydown');
                $('#msg').unbind('keypress',enterSend);
                $('#msg').bind('keydown',ctrlSend);
            }
            //回车发送
            function enterSend(event){
                if(event.keyCode == "13"){
                    event.preventDefault();
                    sendMessage()
                }
            }
            //ctrl+回车发送
            function ctrlSend(event){
                if (event.ctrlKey && event.keyCode == 13) {
                    sendMessage()
                }
            }
            //ctrl+回车换行
            function ctrlN(event){
                if (event.ctrlKey && event.keyCode == 13) {
                    event.preventDefault();
                    // 创建一个新的 Range 对象，设置光标位置为当前光标所在位置的下一行开头
                    const range = window.getSelection().getRangeAt(0);
                    const newLine = document.createElement('div');
                    const br = document.createElement('br');
                    // 将 br 元素插入到 div 元素中
                    newLine.appendChild(br);
                    range.insertNode(newLine);
                    const newRange = document.createRange();
                    newRange.setStart(newLine, 0);
                    newRange.setEnd(newLine, 0);
                    const selection = window.getSelection();
                    selection.removeAllRanges();
                    selection.addRange(newRange);
                }
            }


            //关闭按钮
            $(".layim-session-close").click(function (){
                history.back (-1)
            })
            //点击按钮发送
            $("#send-btn").click(function (){
                sendMessage()
            })


            //聊天发送图片
            layui.use('upload', function(){
                var upload = layui.upload;
                var mydata = new Date();
                var Nowtime = mydata.getDate()+mydata.getTime()
                //执行实例
                var uploadInst = upload.render({
                    elem: '#LAY_messageUpload' //绑定元素
                    ,url: '/public/uploadMessageImg/'//上传接口
                    ,data:{  // 文件上传的参数
                        id: Nowtime,
                        Status:getCookie("Status"),
                        roomId:parent.roomId,
                    }
                    ,done: function(res){
                        layer.msg(res.msg,{icon: res.icon, time: 1000},function(){
                            // window.parent.location.reload()
                            var myDate = new Date;
                            var filePath = "/static/images/room/" + parent.roomId +"/"+ Nowtime +".png"
                            SendTime =myDate.getFullYear()+"-"+(myDate.getMonth()+1)+"-"+myDate.getDate()+" "+myDate.getHours()+":"+myDate.getMinutes()+":"+myDate.getSeconds()
                            var SendTimestamp = new Date().getTime();
                            var json = {"roomId":parent.roomId.toString(),"sender":Id,"senderName":Name,"recipient":to_Id,"content":filePath,"sendTime":SendTime,"type": "pic","SendTimestamp":SendTimestamp}; //创建对象；
                            var jsonStr = JSON.stringify(json);       //转为JSON字符串
                            appendLog(json,"messaging")
                            LastSendMsg = jsonStr
                            conn.send(jsonStr);
                        }); //提交成功后刷新页面
                    }
                    ,error: function(){
                        //请求异常回调
                    }
                });
            });



            //网页大小变化监听
            var resizeTimer;
            window.addEventListener('resize', function(event) {
                clearTimeout(resizeTimer);
                //调整表情框位置
                resizeTimer = setTimeout(function() {
                    var offset=$(".layim-tool-face").offset()
                    $(".emoji-class").css("top",offset.top-200+"px")
                    $(".emoji-class").css("left",offset.left-20+"px")
                }, 100);
            });

            //查看更多消息
            $(".showMoreMsg").click(function (){
                var count = $('.chat-main-context ul li').length;

                // 获取滚动条总长度
                var scrollHeight = $(".chat-main-context ul").height();
                $.ajax({
                    url:'/public/client/GetMoreMessage',
                    method:'POST',
                    dataType:'JSON',
                    data:{
                        RoomId:parent.roomId,
                        MessageCount:count,
                    },
                    success:function(res){
                        for (var i=0;i<=res.data.length-1;i++){
                            var msgobj = JSON.parse(res.data[i])
                            appendLog(msgobj,"history")
                        }
                        var newHeight = $(".chat-main-context ul").height();
                        if (newHeight==scrollHeight){
                            $(".showMoreMsg").css("display","none")
                        }
                        $(".chat-main-context").scrollTop(newHeight-scrollHeight)   //滚动条位置
                    }
                })
            })
        }) //网页加载结束

        //点击图片放大
        function showBigImage(e){
            layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true, //点击阴影关闭
                offset: 'auto',
                content: "<img width='800px' src=" + $(e).attr('src') + " />"
            });
        }
        //获取历史消息
        function getMessages() {
            $.ajax({
                url:'/public/client/GetMessage/'+parent.roomId,
                method:'get',
                dataType:'JSON',
                success:function(res){
                    for (var i=res.data.length-1;i>=0;i--){
                        var msgobj = JSON.parse(res.data[i])
                        appendLog(msgobj,"messaged")
                    }
                }
            })
        }
        //获取聊天对象名字
        function getClientName() {
            $.ajax({
                method: "get",
                url: "/public/client/GetName/"+parent.to_Id,
                dataType:'JSON',
                success: function(res) {
                    $(".layim-chat-username").html(res.Name)
                },
            });
        }
        //检查用户是否在线
        function checkOnline(to_Id) {
            flag="false"
            $.ajax({
                method: "post",
                url: "/public/client/ReturnOnline",
                dataType:'JSON',
                async:false,
                success: function(res) {
                    $.each(res.OnlineList, function(index, item) {
                        if(to_Id == item){
                            flag="ture"
                        }
                    });
                },
            });
            if (flag=="ture"){
                StateOnlineClass()
            }else {
                StateOfflineClass()
            }
        }
        //在线和离线的状态
        function StateOnlineClass() {
            $("#layim-chat-img-state").attr("class","layim-chat-state-online")
            $("#layim-chat-text-state").html("在线")
        }
        function StateOfflineClass() {
            $("#layim-chat-img-state").attr("class","layim-chat-state-offline")
            $("#layim-chat-text-state").html("离线")
        }

        //工具栏
        //聊天表情
        $(".layim-tool-face").click(function (){
            var offset=$(".layim-tool-face").offset()
            $("#chat-emoji-ul").html("")
            foot = $(".chat-footer").position()
            var layer = layui.layer;
            dom ="<ul id=\"chat-emoji-ul\"></ul>"
            layer.open({
                type: 1,
                content: dom,
                skin: 'emoji-class',
                offset: [offset.top-200+"px", offset.left-20+'px'],
                area: ['350px', '200px'],
                shade: [0.0001, '#fff'],
                title: false,
                closeBtn: 0,
                shadeClose:true,
                resize:false,
                move: false,
                success: function(layero, index){
                    //添加表情
                    emojiList =getFaceList()
                    for (var txt in emojiList) {
                        var li = "<li class='chat-emoji-li'><div>"+emojiList[txt]+"</div></li>"
                        $("#chat-emoji-ul").append(li)
                    }
                    //选择表情样式
                    $('.chat-emoji-li').mouseenter(function() {
                        $(this).find("div").addClass("chat-emoji-ul-li-css")
                        $(this).find("img").css("width","38px")
                        $(this).find("img").css("height","38px")
                    });
                    $('.chat-emoji-li').mouseleave(function() {
                        $(this).find("div").removeClass("chat-emoji-ul-li-css")
                        $(this).find("img").css("width","")
                        $(this).find("img").css("height","")
                    });
                    //点击表情
                    $('.chat-emoji-li').click(function (){

                        $(this).find("img").css("width","35")
                        $(this).find("img").css("height","35")
                        $("#msg").focus()
                        const range = window.getSelection().getRangeAt(0);
                        const node = $(this).find("img")[0];
                        range.insertNode(node);
                        range.setStartAfter(node); // 将 Range 的起始位置设置为 img 元素之后的位置
                        range.setEndAfter(node); // 将 Range 的结束位置设置为 img 元素之后的位置
                        const selection = window.getSelection(); // 获取当前的 Selection 对象
                        selection.removeAllRanges(); // 清空当前的选择范围
                        selection.addRange(range); // 将 Range 设置为新的选择范围
                        layer.close(index)
                    })
                }
            });
        })

        //替换输入框中的emoji
        function replaceEmojisWithText(Text){
            // 使用正则表达式查找所有表情符号
            let matches = Text.match(/<img\sclassname="chat-emoji-img"\stitle=".{0,4}"\ssrc=".{0,30}"\sstyle=".{0,30};">/g);
            // 遍历所有匹配项，将其替换为"[xx]"
            if (matches==null){
                return Text
            }
            for (let i = 0; i < matches.length; i++) {
                // console.log(matches[i])
                LeftBracket = matches[i].replace(/<img.*title="/i, "[");
                RightBracket = LeftBracket.replace(/"\ssrc=.*">/i, "]");
                Text = Text.replace(matches[i], RightBracket);
            }
            return Text
        }

        //移除剪切板中的其他样式
        function removeFormatting(e) {
            e.preventDefault();
            const text = e.clipboardData.getData('text/plain');
            document.execCommand('insertText', false, text);
        }
        //替换图片
        function text2pic(txt) {
            if (!txt) {
                return '';
            }
            txt = txt.replace(/\[([^\]]+)\]/g, function (v1, v2) {
                let d = emojiData[v2];
                return d ? '<img class="chat-emoji-img" src="' + getFaceUrl(d) + '" />' : v1;
            });
            return txt;
        }
        //新消息提示
        $(".chat-main-notification").click(function (){
            $(".chat-main-notification").css("display","none")
            $(".chat-main-context").scrollTop(scrollMain().Bottom)
        })


        // 绑定事件处理函数
        $(document).on("click", ".booking-accept-btn", function() {
            var bookingId = $(this).closest(".layui-card-footer").attr("id");
            var sendTimestamp = $(this).closest(".bookingCard").attr("id");
            $.ajax({
                url:'/teacher/updateBooking/'+bookingId+"/2",
                method:'post',
                dataType:'JSON',
                success:function(res){
                    if(res.code=='1'){
                        $.ajax({
                            url:'/teacher/updataRedis/'+sendTimestamp+"/2",
                            method:'get',
                            dataType:'JSON',
                            success:function(res){
                                if(res.code=='1'){
                                    layer.msg(res.msg,{icon: res.code, time: 1000},function(){
                                        location.reload ()
                                    });
                                }
                                else{
                                    layer.msg(res.msg,{icon: res.code, time: 1000},function(){});
                                }
                            },
                        });
                    }
                    else{
                        layer.msg(res.msg,{icon: res.code, time: 1000},function(){});
                    }
                },
            });
            // 点击接受按钮后的处理逻辑
        });

        $(document).on("click", ".booking-accept-refuse", function() {
            var bookingId = $(this).closest(".layui-card-footer").attr("id");
            var sendTimestamp = $(this).closest(".bookingCard").attr("id");
            layer.confirm('你确定要该预约拒绝吗', function(index){
                $.ajax({
                    url:'/teacher/updateBooking/'+bookingId+"/4",
                    method:'post',
                    dataType:'JSON',
                    success:function(res){
                        if(res.code=='1'){
                            $.ajax({
                                url:'/teacher/updataRedis/'+sendTimestamp+"/4",
                                method:'get',
                                dataType:'JSON',
                                success:function(res){
                                    if(res.code=='1'){

                                        layer.msg(res.msg,{icon: res.code, time: 1000},function(){
                                            location.reload ()
                                        });
                                    }
                                    else{
                                        layer.msg(res.msg,{icon: res.code, time: 1000},function(){});
                                    }
                                },
                            });
                        }
                        else{
                            layer.msg(res.msg,{icon: res.code, time: 1000},function(){});
                        }
                    },
                });
            });// 点击拒绝按钮后的处理逻辑
        });

    </script>
    <style type="text/css">
        html {
            overflow: hidden;
        }
        body {
            overflow: hidden;
            padding: 0;
            margin: 0;
            width: 100%;
            height: 100%;
            background: gray;
        }
        #log {
            background: white;
            margin: 0;
            position: absolute;
            top: 50%;
            left: 50%;
            overflow: auto;
            min-width: 500px;
            min-height: 300px;
            border-radius: 5px;
            transform: translate(-50%,-50%);
            width: 80%;
            height: 90%;
            max-width: 1200px;
            max-height: 800px;
        }
        .chat-footer{
            margin: 0;
            position: absolute;
            bottom: 0em;
            overflow: hidden;
            height: 150px;
            left: 0em;
            right: 0em;
            background-color: rgba(245,245,245,.7);
            border-top: 1px solid #d9d9d9;
        }
        .chat-tool{
            position: relative;
            padding: 0 8px;
            height: 38px;
            line-height: 38px;
            font-size: 0;
        }
        .chat-tool span{
            position: relative;
            margin: 0 10px;
            display: inline-block;
            *display: inline;
            *zoom: 1;
            vertical-align: top;
            font-size: 24px;
            cursor: pointer;
        }
        .chat-textarea{
            margin-left: 10px;
        }
        #msg{
            display: block;
            width: 100%;
            padding: 5px 0 0;
            height: 68px;
            line-height: 20px;
            border: none;
            overflow: auto;
            resize: none;
            background: 0 0;
            outline: none;
        }
        .chat-bottom{
            position: relative;
            height: 46px;
        }
        .chat-input{
            position: absolute;
            right: 15px;
            top: 3px;
            height: 32px;
            line-height: 32px;
            font-size: 0;
            cursor: pointer;
        }
        .layim-session-close {
            display: inline-block;
            *display: inline;
            *zoom: 1;
            vertical-align: top;
            font-size: 14px;
            line-height: 32px;
            margin-left: 5px;
            padding: 0 20px;
            background-color: #5FB878;
            color: #fff;
            border-radius: 3px;
        }
        .layim-session-send{
            display: inline-block;
            *display: inline;
            *zoom: 1;
            vertical-align: top;
            font-size: 14px;
            line-height: 32px;
            margin-left: 5px;
            padding: 0 20px;
            background-color: #5FB878;
            color: #fff;
            border-radius: 3px 0 0 3px;

        }
        .layim-session-set{
            position: relative;
            width: 30px;
            height: 32px;
            margin-left: 0;
            padding: 0;
            display: inline-block;
            border-left: 1px solid #85C998;
            border-radius: 0 3px 3px 0;
            background-color: #5FB878;
            color: #fff;
        }
        .layui-edge{
            position: absolute;
            top: 14px;
            left: 9px;
            border-width: 6px;
            border-top-style: solid;
            border-top-color: #fff;
        }
        .chat-title{
            height: 80px;
            border-bottom: none;
            background-color: #F8F8F8;
            background-color: rgba(245,245,245,.7);
            line-height: normal;
            border-bottom: 1px solid #e5e5e5;
        }
        .layim-chat-other img {
            position: absolute;
            left: 0;
            top: 0;
            width: 50px;
            height: 50px;
            border-radius: 100%;
        }
        .layim-chat-other {
            position: relative;
            top: 15px;
            left: 15px;
            padding-left: 60px;
        }
        .layim-chat-username {
            position: relative;
            top: 5px;
            font-size: 18px;
        }
        .layim-chat-status {
            margin-top: 6px;
            font-size: 14px;
            color: #999;
        }
        .layim-chat-title {
            position: absolute;
            height: 80px;
        }
        .chat-main{
            position: relative;
        }
        .chat-main-context{
            position: absolute;
            top: 0em;
            left: 0em;
            right: 0em;
            bottom: 0em;
            overflow-y: auto;
            overflow-x: hidden;
            padding:0 1em ;
            background-color: rgba(245,245,245,.7);
        }
        .chat-main-context pre{
            font: 14px Helvetica Neue,Helvetica,PingFang SC,Tahoma,Arial,sans-serif;
            line-height: 24px;
        }
        .chat-main ul li{
            position: relative;
            font-size: 0;
            margin-bottom: 10px;
            padding-left: 60px;
            min-height: 68px;
        }
        .layim-chat-user img {
            width: 40px;
            height: 40px;
            border-radius: 100%;
        }
        .layim-chat-user {
            position: absolute;
            left: 3px;
        }
        .layim-chat-user cite {
            position: absolute;
            left: 60px;
            top: -2px;
            width: 500px;
            line-height: 24px;
            font-size: 12px;
            white-space: nowrap;
            color: #999;
            text-align: left;
            font-style: normal;
        }
        .layim-chat-user cite i {
            padding-left: 15px;
            font-style: normal;
        }
        .layim-chat-state {
            position: relative;
            line-height: 22px;
            margin-top: 25px;
            padding: 8px 8px;
            color: #333;
            word-break: break-all;
            display: inline-block;
            *display: inline;
            *zoom: 1;
            vertical-align: top;
            font-size: 25px;
            max-width: 60%;
            min-height: 22px;
        }
        .layim-chat-state i{
            font-size: 25px;
        }
        .layim-chat-text {
            position: relative;
            line-height: 22px;
            margin-top: 25px;
            padding: 6px 10px;
            background-color: #e2e2e2;
            border-radius: 3px;
            color: #333;
            word-break: break-all;
            display: inline-block;
            *display: inline;
            *zoom: 1;
            vertical-align: top;
            font-size: 14px;
            max-width: 60%;
            min-height: 22px;
        }
        .layim-chat-text:after {
            content: '';
            position: absolute;
            left: -10px;
            top: 13px;
            width: 0;
            height: 0;
            border-style: solid dashed dashed;
            border-color: #e2e2e2 transparent transparent;
            overflow: hidden;
            border-width: 10px;
        }

        .chat-main ul .layim-chat-mine {
            text-align: right;
            padding-left: 0;
            padding-right: 60px;
        }
        .layim-chat-mine .layim-chat-user cite i {
            padding-left: 0;
            padding-right: 15px;
        }
        .layim-chat-mine .layim-chat-text {
            margin-left: 0;
            text-align: left;
            background-color: #5FB878;
            color: #fff;
        }
        .layim-chat-mine .layim-chat-text:after {
            left: auto;
            right: -10px;
            border-top-color: #5FB878;
        }
        .layim-chat-mine .layim-chat-user {
            left: auto;
            right: 3px;
        }
        .layim-chat-mine .layim-chat-user cite {
            left: auto;
            right: 60px;
            text-align: right;
        }
        /* 整个滚动条 */
        .chat-main-context::-webkit-scrollbar {
            /* 对应纵向滚动条的宽度 */
            width: 8px;
            /* 对应横向滚动条的宽度 */
            height: 8px;
        }

        /* 滚动条上的滚动滑块 */
        .chat-main-context::-webkit-scrollbar-thumb {
            background-color: #49b1f5;
            border-radius: 32px;
        }

        /* 滚动条轨道 */
        .chat-main-context::-webkit-scrollbar-track {
            background-color: rgba(245,245,245,.7);
            border-radius: 32px;
        }
        .layim-chat-state-online{
            position: absolute;
            width: 10px;
            height: 10px;
            right: 2px;
            bottom: 0px;
            background-color: #1bfb00;
            border-radius: 100%;
        }
        .layim-chat-state-offline{
            position: absolute;
            width: 10px;
            height: 10px;
            right: 2px;
            bottom: 0px;
            background-color: #8d8d8d;
            border-radius: 100%;
        }
        .chat-emoji-img{
            width: 24px;
            height: 24px;
        }
        #chat-emoji-ul li{
            width: 37px;
            height: 37px;
            float: left;
            padding: 3px;
            margin: 3px;
        }
        #chat-emoji-ul li div{
            width: 38px;
            height: 38px;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            border-radius: 5px;
        }
        #chat-emoji-ul li img{
            width: 35px;
            height: 35px;
        }

        .chat-emoji-ul-li-css{
            background-color: #DCDCDC;
        }
        .chat-emoji-ul-li-img-css{
            width: 38px;
            height: 38px;
        }
        /* emoji弹出层样式 */
        body .emoji-class{
            border-radius: 10px;
        }
        body .emoji-class .layui-layer-content{
            padding-right: 7px;
            overflow: hidden;
        }
        /* 整个滚动条 */
        body .emoji-class .layui-layer-content::-webkit-scrollbar{
            /* 对应纵向滚动条的宽度 */
            width: 7px;
            /* 对应横向滚动条的宽度 */
            height: 7px;
        }
        /* 滚动条上的滚动滑块 */
        body .emoji-class .layui-layer-content::-webkit-scrollbar-thumb {
            background-color: #d2d2d2;
            border-radius: 32px;
        }

        /* 滚动条轨道 */
        body .emoji-class .layui-layer-content::-webkit-scrollbar-track {
            background-color: #FFFFFF;
            border-radius: 32px;
        }
        body .emoji-class .layui-layer-content:hover{
            padding: 0;
            overflow-y: auto;
        }

        .chat-main-notification{
            border-radius: 25px;
            width: 120px;
            position: absolute;
            left: 50%;
            bottom: 2%;
            transform: translate(-50%, 0%);
            display: none;
            z-index: 99;
            padding: 0;
        }
        .layui-menu li{
            font-size: 8px;
        }
        #Enter,#CtrlEnter{
            padding-right: 5px;
            font-weight: 700;
            color: #5FB878;
        }
        .layim-chat-pic img{
            margin-top: 24px;
            border-radius: 5px;
            border: 1px solid #E5E5E5;
        }
        .bookingCard{
            width: 35%;
            padding: 10px;
            margin-left: 50%;
            transform: translateX(-50%);
            box-shadow: 1px 1px 4px rgb(0 0 0 / 8%);
            border-radius: 5px;

        }
        .layui-card:last-child {
            margin-bottom: 20px;
        }
    </style>
</div>

</body>
</html>